﻿using PowerHub.MES.DTO.Crew.QueryDto;
using PowerHub.MES.EFBase;
using PowerHub.MES.Entities.Crew;
using PowerHub.MES.Entities;
using PowerHub.MES.IRepository.ICrew;
using PowerHub.MES.ReturnEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PowerHub.MES.DTO.Production.QueryDTO;
using PowerHub.MES.Entities.Production;
using Microsoft.EntityFrameworkCore;
using PowerHub.MES.IRepository.IProduction;
using PowerHub.MES.Common.Utility;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace PowerHub.MES.Repository.Production
{
    /// <summary>
    ///生产任务数据实现层
    /// </summary>
    public class Production_ProductionTaskRepository : BaseRepository<Production_ProductionTask>, IProduction_ProductionTaskRepository
    {
        private PowerHubMesContext _repositorySys;
        public Production_ProductionTaskRepository(PowerHubMesContext repositorySys) : base(repositorySys)
        {
            _repositorySys = repositorySys;
        }


        /// <summary>
        /// 添加生产任务
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationResult<bool>> CreateProduction_ProductionTaskAsync(List<Production_ProductionTask> query)
        {
            var result = new OperationResult<bool>();
            result.Data = false;

            if (AddEntitieRange(query) > 0)
            {
                result.Data = true;
            }

            return result;
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationResult<bool>> DeletionProduction_ProductionTaskAsync(List<string>? ids)
        {
            var result = new OperationResult<bool>();

            var Departments = GetEntitys().AsNoTracking().Where(p => ids.Contains(p.Id)).ToList();
            Departments.ForEach(w => w.IsDel = 1);
            result.Data = UpdataEntityRange(Departments) > 0 ? true : false;

            return result;
        }

        /// <summary>
        /// 获取生产任务列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationPageResult<List<Production_ProductionTask>>> GetProduction_ProductionTaskPageListAsync(QueryProduction_ProductionTaskDTO query)
        {
            var result = new OperationPageResult<List<Production_ProductionTask>>();

            var currentQuery = GetEntitys().AsNoTracking()
                                            .Where(p => p.IsDel == 0)
                                            .WhereIf(!string.IsNullOrEmpty(query.WorkOrderId), p => p.WorkOrderId.Equals(query.WorkOrderId))
                                            .Include(p => p.Userinfo)
                                            .Include(p => p.SchedulingPlan)
                                            .Include(p => p.WorkOrder)
                                            //.Include(p=>p.ProductBill)
                                            .Include(p => p.Process)
                                            .Include(p => p.WorkStation);

            result.PageIndex = query.PageIndex;
            result.PageSize = query.PageSize;
            result.TotalCount = await currentQuery.CountAsync();

            if (result.TotalCount > 0)
            {
                result.Data = await currentQuery.OrderByDescending(g => g.Createtime).Skip((query.PageIndex - 1) * query.PageSize).Take(query.PageSize).ToListAsync();
            }

            return result;
        }

        /// <summary>
        /// 更新生产任务
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationResult<bool>> UpdateProduction_ProductionTaskAsync(Production_ProductionTask query)
        {
            var result = new OperationResult<bool>();
            result.Data = false;
            if (UpdataEntity(query) > 0)
            {
                result.Data = true;
            }
            return result;
        }


        /// <summary>
        /// 获取工单BOM信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<Production_BillOfMaterials> GetProduction_BillOfMaterialsByIdAsync(string id)
        {
            return _repositorySys.Set<Production_BillOfMaterials>().AsNoTracking().FirstOrDefault(g => g.Id.Equals(id));
        }

        /// <summary>
        /// 根据计划明细id添加生产任务（单）
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<OperationResult<bool>> CreateProduction_ProductionTaskBySchedulingPlanDetialIdAsync(bool isUpdate, Production_ProductionTask production_ProductionTask, Crew_SchedulingPlanDetial schedulingPlanDetial, Production_BillOfMaterials billOfMaterials)
        {
            var result = new OperationResult<bool>();
            result.Data = false;

            using (var tran = _repositorySys.Database.BeginTransaction())
            {
                try
                {
                    // 任务
                    if (isUpdate)
                    {
                        _repositorySys.Set<Production_ProductionTask>().Add(production_ProductionTask);
                    }

                    // 计划明细
                    _repositorySys.Set<Crew_SchedulingPlanDetial>().Update(schedulingPlanDetial);

                    // 工单BOM
                    _repositorySys.Set<Production_BillOfMaterials>().Update(billOfMaterials);

                    // 保存更改
                    _repositorySys.SaveChanges();

                    // 提交事务
                    tran.Commit();
                    result.Data = true;
                }
                catch (Exception ex)
                {
                    // 回滚事务
                    tran.Rollback();
                    result.Message = ex.Message;
                }
            }

            return result;
        }
    }
}
